package com.gongj.deadletter.mq.cousumer;


import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 消费者
 */
@Component
@Slf4j
public class RabbitReceiver {
    int count  = 0;

    //测试重试
    @RabbitListener(queues = "${mq.queueBinding.queue}")
    public void infoConsumption(String data, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception {
        log.info("重试次数 = {}",count++);
        int i = 10 /0;
        channel.basicAck(tag,false);
    }

    //测试消费者进行消费发送异常 是否进入死信队列
//    @RabbitListener(queues = "${mq.queueBinding.queue}")
//    public void infoConsumption(String data, Channel channel,@Headers Map<String,Object> headers) throws Exception {
//        log.info("收到信息:{}",data);
//        boolean ack = false;
//        Exception exception = null;
//        try {
//            if(data.contains("888")){
//               throw new RuntimeException("信息敏感");
//            }
//        } catch (RuntimeException e) {
//            ack = true;
//            exception = e;
//        }
//        for(Map.Entry<String, Object> map :headers.entrySet()){
//            log.info(map.getKey() + " ===> " + map.getValue());
//        }
//        // 睡眠两秒
//        Thread.sleep(2000);
//        Long tag = (Long) headers.get("amqp_deliveryTag");
//        if (ack){
//            log.error("消息消费发生异常，error msg:{}", exception.getMessage(), exception);
//            //注意第三个参数需要为false
//            //true则重新放入原队列，否则丢弃或者进入死信队列。
//            log.error("消息消费发生异常");
//            channel.basicNack(tag, false, true);
//        } else {
//            //进行手动确认信息已经被消费
//            channel.basicAck(tag, false);
//        }
//    }
}
